% The code is based on the following paper:
%   Chen, T. Y., Lin, Y. L., and Tzeng, L. Y., forthcoming.
%   Estimating probability weighting functions through option pricing bounds. Review of Asset Pricing Studies.
%
% Copyright: Tzu-Ying Chen, Yo-Lan Lin, Larry Y. Tzeng
% Date: January 30, 2024

clear

%% Load Data
FileName = ['AllTradingDate19962021_Monthly.mat'];
load(FileName, ...
     'Target_AllDate');             
clear FileName

%% Load Data 
AllData = [];                                                             
for d = 1:size(Target_AllDate, 1)
    Target_Date = Target_AllDate(d, 1);
    Target_TTM = Target_AllDate(d, 3);

    FileName = ['OP' num2str(Target_Date) '_TTM' num2str(Target_TTM) '.mat'];
    load(FileName, ...
         'Data', ...
         'Index_Date', 'Index_TTM', 'Index_CPFlag', 'Index_K', 'Index_OP_Bid', 'Index_OP_Ask', ...
         'Index_RF', 'Index_DY', 'Index_IS', 'Index_IS_ADJ', 'Index_IV_Bid', 'Index_IV_Ask');
    clear FileName 

    Index_Drop = find(sum(isnan(Data(:, [Index_IV_Bid Index_IV_Ask])), 2) > 0);
    Data(Index_Drop, :) = [];                                              
    AllData = [AllData; Data];
    clear Index_Drop Data
    clear Target_Date Target_TTM     
end
clear Target_AllDate
clear d

%% Summary Statistics
[AllYear, ~, Index_AllYear]= unique(fix(AllData(:, Index_Date) / 10000));
IV = AllData(:, Index_IV_Bid);

TAB = [accumarray(Index_AllYear, 1, size(AllYear), @sum, nan) ...
       accumarray(Index_AllYear, IV, size(AllYear), @mean, nan) ...
       accumarray(Index_AllYear, IV, size(AllYear), @min, nan) ...
       accumarray(Index_AllYear, IV, size(AllYear), @max, nan)];
clear AllYear Index_AllYear IV

clear AllData
clear Index_ID Index_Date Index_TTM Index_CPFlag Index_K Index_S Index_F Index_OP_Bid Index_OP_Ask Index_OI Index_V
clear Index_RF Index_DY Index_IS Index_IS_ADJ Index_S_ADJ Index_IV_Bid Index_IV_Ask
